<script lang="ts" setup>
import {
  ElMessageBox,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElUpload,
  ElTabs,
  ElTabPane,
  ElMessage,
  ElRow,
  ElCol,
  ElDivider,
  ElIcon,
  ElSelect,
  ElOption,
} from "element-plus";
import { reactive, ref } from "vue";
import { router } from "#/router";
import { addDrone, editDrone, getDroneById } from "#/api/sys/equipment";
import Upload from "#/adapter/component/Upload/Upload.vue";
const disabled = ref(false);
const acceptImg = ref(".jpg,.jpeg,.png");
const isShowTip = reactive({
  isShow: false,
  message: "",
});

const activeName = ref("first");
const ruleFormRef = ref();
const ruleForm = reactive<RuleForm>({
  id: router.currentRoute.value.query.id
    ? +router.currentRoute.value.query.id
    : "",
  droneName: "",
  droneBrand: "",
  droneModel: "",
  droneSn: "",
  droneImage: "",
});

const modelList = [
  { label: "大疆", value: "大疆" },
];

const droneModelList = [
  {
    label: "M350 RTK",
    value: "M350 RTK",
  },
  {
    label: "M300 RTK",
    value: "M300 RTK",
  },
  {
    label: "M30/M30T",
    value: "M30/M30T",
  },
  {
    label: "M3E/M3T/M3M",
    value: "M3E/M3T/M3M",
  },
  {
    label: "M3D/M3TD",
    value: "M3D/M3TD",
  },
  {
    label: "Matrice 4TD",
    value: "Matrice 4TD",
  },
];
const spaceInput = (field: string, value: string) => {
  // 过滤空格
  ruleForm[field] = value.replace(/\s+/g, "");
};
const updateImg = (img) => {
  ruleForm.droneImage = img;
};

const getDetail = async (id) => {
  const params = {
    id: id,
  };
  const { data } = await getDroneById(params);
  ruleForm.droneName = data.droneName;
  ruleForm.droneBrand = data.droneBrand;
  ruleForm.droneModel = data.droneModel;
  ruleForm.droneSn = data.droneSn;
  ruleForm.droneImage = data.imageUrl;
  ruleForm.id = data.id;
};

const title = ref("添加无人机");
if (ruleForm.id) {
  title.value = "编辑无人机";
  getDetail(router.currentRoute.value.query.id);
}

const rules = reactive({
  droneName: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { min: 1, max: 20, message: "请输入最多20字", trigger: "blur" },
  ],
  droneBrand: [
    { required: true, message: "请选择无人机品牌", trigger: "change" },
  ],
  droneModel: [
    { required: true, message: "请选择无人机型号", trigger: "change" },
  ],
  droneSn: [
    { required: true, message: "请输入无人机序列号", trigger: "blur" },
    { min: 1, max: 20, message: "请输入最多20字", trigger: "blur" },
  ],
});

const loading = ref(false);

const addForm = () => handleSubmit(false);
const editForm = () => handleSubmit(true);

const buildFormParams = (isEdit: boolean) => ({
  ...(isEdit && { id: ruleForm.id }),
  droneName: ruleForm.droneName,
  droneBrand: ruleForm.droneBrand,
  droneModel: ruleForm.droneModel,
  droneSn: ruleForm.droneSn,
  imageUrl: ruleForm.droneImage,
});

const handleApiResponse = (isEdit: boolean) => {
  ElMessage.success(isEdit ? "修改成功" : "添加成功");
  // 通知列表页刷新数据
  window.dispatchEvent(new Event('refreshUvaList'));
  handleBack();
};

const submitForm = async (isEdit = false) => {
  if (loading.value) return;

  try {
    loading.value = true;
    await ruleFormRef.value?.validate();

    const params = buildFormParams(isEdit);
    const { code, msg } = isEdit
      ? await editDrone(params)
      : await addDrone(params);

    if (code == 200) handleApiResponse(isEdit);
    else ElMessage.error("操作失败," + msg);
  } catch (error) {
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};

const resetForm = (formEl) => {
  if (!formEl) return;
  ruleFormRef.value.resetFields();
};

const fileList = ref([]);
const handlePreview = (file) => {
  imageUrl.value = file.url;
};
const handleRemove = (file, fileList) => {
  //   fileList.value = fileList.value.filter((item) => item.uid !== file.uid);
};
const handleChange = (file, fileList) => {
  //   fileList.value = fileList.value.slice(-1);
};
const beforeUpload = (file) => {};
const handleBack = () => {
  router.go(-1);
};
</script>

<template>
  <div class="detailPage mg-10 pd-20">
    <div class="backBtn">
      <Back width="18px" hight="18px" />
      <ElButton class="btn" @click="handleBack()">返回</ElButton>
    </div>
    <ElTabs v-model="activeName" class="demo-tabs">
      <ElTabPane :label="title" name="first">
        <div class="page">
          <h3 class="title">无人机信息</h3>
          <ElForm
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
          >
            <ElRow>
              <ElCol
                :xs="24"
                :sm="12"
                :md="12"
                :lg="12"
                :xl="12"
                class="searchCol"
              >
                <ElFormItem label="无人机名称：" prop="droneName">
                  <ElInput
                    v-model="ruleForm.droneName"
                    placeholder="请输入无人机名称"
                    style="width: 300px"
                    @input="(value) => spaceInput('droneName', value)"
                  />
                </ElFormItem>
              </ElCol>
              <ElCol
                :xs="24"
                :sm="12"
                :md="12"
                :lg="12"
                :xl="12"
                class="searchCol"
              >
                <ElFormItem label="无人机品牌：" prop="droneBrand">
                  <!-- <ElInput
                    v-model="ruleForm.droneBrand"
                    placeholder="请输入无人机品牌"
                    style="width: 300px"
                    @input="(value) => spaceInput('droneBrand', value)"
                  /> -->
                  <ElSelect
                    v-model="ruleForm.droneBrand"
                    placeholder="请选择无人机品牌"
                    style="width: 300px"
                  >
                    <ElOption
                      v-for="item in modelList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </ElSelect>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow>
              <ElCol
                :xs="24"
                :sm="12"
                :md="12"
                :lg="12"
                :xl="12"
                class="searchCol"
              >
                <ElFormItem label="无人机型号：" prop="droneModel">
                  <!-- <ElInput
                    v-model="ruleForm.droneModel"
                    placeholder="请输入无人机型号"
                    style="width: 300px"
                  /> -->
                  <ElSelect
                    v-model="ruleForm.droneModel"
                    placeholder="请选择无人机型号"
                    style="width: 300px"
                  >
                    <ElOption
                      v-for="item in droneModelList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </ElSelect>
                </ElFormItem>
              </ElCol>
              <ElCol
                :xs="24"
                :sm="12"
                :md="12"
                :lg="12"
                :xl="12"
                class="searchCol"
              >
                <ElFormItem label="无人机序列号：" prop="droneSn">
                  <ElInput
                    v-model="ruleForm.droneSn"
                    placeholder="请输入无人机序列号"
                    style="width: 300px"
                    @input="(value) => spaceInput('droneSn', value)"
                  />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow>
              <ElFormItem label="无人机图片：" prop="droneImage">
                <Upload
                  v-model:imgUrl="ruleForm.droneImage"
                  :isShowTip="isShowTip"
                  :disabled="disabled"
                  :accept="acceptImg"
                  @updateImg="updateImg"
                />
              </ElFormItem>
            </ElRow>
          </ElForm>
        </div>
      </ElTabPane>
    </ElTabs>
    <div class="buts">
      <ElDivider />
      <ElButton @click="resetForm(ruleFormRef)">清空</ElButton>
      <ElButton
        type="primary"
        @click="() => submitForm(title !== '添加无人机')"
        :loading="loading"
      >
        确定
      </ElButton>
    </div>
  </div>
</template>
<style scoped>
h1 {
  margin-bottom: 20px;
  font-weight: 900;
}

.title {
  padding: 8px 10px;
  margin-bottom: 16px;
  font-size: 14px;
  background: #f5f7fa;
}

.buts {
  position: absolute;
  bottom: 20px;
  left: 50%;
  width: 100%;
  text-align: center;
  transform: translateX(-50%);
}

.avatar-uploader-icon {
  width: 2rem;
  height: 2rem;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}

.logo-uploader {
  display: block;
  width: 148px;
  height: 148px;
}

.logo-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
</style>
